import * as Koa from 'koa';
import { addUploadLog, delUploadLog, updateUploadLog, searchUploadLog } from "../entity/upload-log";
import { joinDefaultFields } from "../utils/index";
const dayjs = require("dayjs");
// TODO：commonjs 模式下引用 esmodule 模块
let nanoid: any = null;
(async () => {
  nanoid = (await eval("import('nanoid')")).nanoid;
})();

const errorMsg = `服务器错误：${'upload-log'}`;
const successMsg = `成功：${'upload-log'}`;

export default class UploadLogService {
  /**
   * 设置图片为upload-log
   * @param ctx 
   * @returns 
   */
  addUploadLog = async (ctx: Koa.Context) => {
    try {
      const uploadLogInfo = ctx.request.body;
      const _uploadLogInfo = joinDefaultFields(uploadLogInfo, "uploadLogFields");
      _uploadLogInfo.ulid = nanoid(18);
      _uploadLogInfo.create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      const result: any = _uploadLogInfo && await addUploadLog(ctx, _uploadLogInfo);
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg ||errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  /**
   * 删除
   * @param ctx 
   */
  delUploadLog = async (ctx: Koa.Context) => {
    try {
      const { ulid } = ctx.request.body;
      if (!ulid || !ulid.length) return ctx.fail(null, "ulid不能为空", -1);
      const ulids = Array.isArray(ulid)? ulid : [ulid];
      let condition = `ulid IN (${ulids.map((i) => `"${i}"`).join(",")})`;
      const result: any =  !!ulids.length && await delUploadLog(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  /**
   * 修改
   * @param ctx 
   */
  updateUploadLog = async (ctx: Koa.Context) => {
    ctx.success(null, successMsg);
  };

  /**
   * 查询
   * @param ctx 
   */
  searchUploadLog = async (ctx: Koa.Context) => {
    try {
      const params = ctx.request.body;
      const { ulid, message, status, create_time, pageNumber, pageSize } = params || {}; // 查询条件
      if (!pageNumber || !pageSize) return ctx.fail(null, "currentPage、pageSize不能为空", -1);
      // 相等的条件
      let condition = "";
      let equals: string | string[] = [];
      ulid && (equals.push(` ulid = "${ulid}"`));
      status && (equals.push(` status = "${status}"`));
      message && (equals.push(` message LIKE "%${message}%"`));
      equals = equals.join(" AND");
      equals && (condition += `WHERE ${equals}`);
      // 排序的条件
      condition += ` ORDER BY create_time DESC`;
      // 分页的条件
      condition += ` LIMIT ${pageSize} OFFSET ${(pageNumber - 1) * pageSize}`;
      const result: any = await searchUploadLog(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success({
          list: result.data || [],
          pageNumber: pageNumber,
          pageSize: pageSize,
        }, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };
}
